/*
 * @(#)TestsetTranslator.java
 *
 *
 *
 * ver 1.0 Sep 4, 2007 ggranum
 */
package org.testfire.realm.view.json.translator;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.testfire.realm.model.entities.testfire.TestEntity;
import org.testfire.realm.model.entities.testfire.TestsetEntity;
import org.testfire.realm.util.json.JsonField;
import org.testfire.realm.util.json.Tools;
import org.testfire.realm.view.tags.util.JavaScriptUtilities;

// eof: TestsetTranslator.java

/**
 * Application Scope
 *
 */
public class TestTranslator implements JsonTranslator<TestEntity>
{

    static final List<JsonField> ALL_FIELDS = new ArrayList<JsonField>();

    static
    {
        ALL_FIELDS.add( new JsonField( "id", JsonField.TYPE_INT ) );
        ALL_FIELDS.add( new JsonField( "name", JsonField.TYPE_STRING ) );
        ALL_FIELDS.add( new JsonField( "forbug", JsonField.TYPE_STRING ) );
        ALL_FIELDS.add( new JsonField( "description", JsonField.TYPE_STRING ) );
        ALL_FIELDS.add( new JsonField( "created", JsonField.TYPE_DATE ) );
    }

    public String toJson( TestEntity object )
    {
        return Tools.getJsonString( object, ALL_FIELDS );
    }

    public String toJson( TestEntity object, String fields ) throws JSONException
    {
        return Tools.getJsonString( object, fields );
    }

    public String toJson( List<TestEntity> objects )
    {
        return Tools.getJsonString( objects, ALL_FIELDS );
    }

    public String toJsonArray( List<TestEntity> objects, String fields ) throws JSONException
    {
        return Tools.getJsonString( objects, fields );
    }

    public TestEntity toObject( String json ) throws JSONException
    {
        JSONObject obj = new JSONObject( json );
        TestEntity test = new TestEntity();
        int id = (Integer)obj.get( "id" );
        Date created;
        try
        {
            created = JavaScriptUtilities.toDateTime( (String)obj.get( "created" ) );
        }
        catch ( ParseException e )
        {
            throw new RuntimeException( e );

        }
        test.setId( id );
        test.setCreated( new Timestamp( created.getTime() ) );

        test.setForbug( (String)obj.get( "forbug" ) );
        test.setDescription( (String)obj.get( "description" ) );
        test.setName( (String)obj.get( "name" ) );
        return test;
    }

    public TestEntity copyValues( TestEntity to, TestEntity from )
    {
        to.setCreated( from.getCreated() );
        to.setDescription( from.getDescription() );
        to.setForbug( from.getForbug() );
        // don't set id
        to.setName( from.getName() );
        // all other setters are for collections, not directly editable by user.
        return to;
    }


}